<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class SalesStrategyViewPermissions extends Model
{
    protected $table = 'sales_strategy_view_permissions';
    
    protected $fillable = [
        'store_id', 
        'store_name',
        'goods_ids'
    ];
    
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳


    /**
     * 获取列表
     */
    /**
     * 批量取消权限
     */
    public function batchRevokePermission()
    {
        $request = request();
        $storeId = $request->store_id;
        $type = $request->type; // 'page' 或 'all'
        $goodsIds = $request->goods_ids ?: [];

        $permission = SalesStrategyViewPermissions::where('store_id', $storeId)->first();

        if (!$permission) {
            return response()->json([
                'code' => 0,
                'msg' => '未找到该代理商的权限记录'
            ]);
        }

        $currentGoodsIds = explode(',', $permission->goods_ids);

        if ($type === 'all') {
            // 取消全部权限
            $newGoodsIds = [];
        } else {
            // 取消选中权限
            $newGoodsIds = array_diff($currentGoodsIds, $goodsIds);
        }

        $permission->goods_ids = implode(',', array_filter($newGoodsIds));
        $permission->save();

        return response()->json([
            'code' => 1,
            'msg' => '操作成功',
            'data' => [
                'revoked_count' => count($currentGoodsIds) - count($newGoodsIds)
            ]
        ]);
    }

    /**
     * 更新单个商品权限状态
     */
    public function updateGoodsPermission()
    {
        $request = request();
        $storeId = $request->store_id;
        $goodsId = $request->goods_id;
        $status = $request->status;

        $permission = SalesStrategyViewPermissions::where('store_id', $storeId)->first();

        if (!$permission) {
            $permission = new SalesStrategyViewPermissions();
            $permission->store_id = $storeId;
            $permission->goods_ids = '';
            $permission->store_name = Store::where('id', $storeId)->value('store_name') ?? '';
        }

        $goodsIds = explode(',', $permission->goods_ids);

        if ($status) {
            // 添加权限
            if (!in_array($goodsId, $goodsIds)) {
                $goodsIds[] = $goodsId;
            }
        } else {
            // 取消权限
            $goodsIds = array_diff($goodsIds, [$goodsId]);
        }

        $permission->goods_ids = implode(',', array_filter($goodsIds));
        $permission->save();

        return response()->json([
            'code' => 1,
            'msg' => '操作成功'
        ]);
    }

    /**
     * 获取分页列表
     */
    public static function getPageList($where = [], $limit = 10)
    {
        $permission = self::where('store_id', $where['store_id'])->first();
        $goodsIds = $permission ? explode(',', $permission->goods_ids) : [];

        // 获取所有有效商品
        $query = Goods::where("status", 1)
            ->select(['id as goods_id', 'cate_id', 'goods_name', 'goods_sn'])
            ->orderBy('id', 'desc');

        // 安全地添加权限标记
        if (!empty($goodsIds)) {
            $query->selectRaw('IF(id IN ('.implode(',', $goodsIds).'), 1, 0) as has_permission');
        } else {
            $query->selectRaw('0 as has_permission');
        }

        // 添加筛选条件
        if (!empty($where['cate_id'])) {
            $query->where('cate_id', $where['cate_id']);
        }
        if (!empty($where['goods_name'])) {
            $query->where('goods_name', 'like', '%'.$where['goods_name'].'%');
        }
        if (!empty($where['goods_sn'])) {
            $query->where('goods_sn', $where['goods_sn']);
        }
        if (!empty($where['has_permission'])) {
            $hasPermission = $where['has_permission'] == 1;
            $query->whereRaw('IF(id IN ('.implode(',', $goodsIds).'), 1, 0) = ?', [$hasPermission ? 1 : 0]);
        }

        if ($limit == 0) {
            $goodsList = $query->get();
        } else {
            $goodsList = $query->paginate($limit);
        }

        // 添加店铺信息
        if ($permission && $goodsList) {
            $goodsList->store_name = $permission->store_name;
            $goodsList->store_id = $permission->store_id;
        }

        return $goodsList;
    }



    /**
     * 创建代理商
     * @param $data
     */
    public static function addInfo($data)
    {
        $info['store_sn'] = $data['store_sn'];
        $info['store_name'] = $data['store_name'];
        $info['money_goods'] = $data['money_goods'] ?: 0;
        $info['money_management'] = $data['money_management'] ?: 0;
        $info['principal_name'] = $data['principal_name'];
        $info['principal_mobile'] = $data['principal_mobile'];
        $info['principal_email'] = $data['principal_email'];
        $info['principal_address'] = $data['principal_address'];
        $info['principal_card_sn'] = $data['principal_card_sn'];
        $info['principal_card_a'] = $data['principal_card_a'];
        $info['principal_card_b'] = $data['principal_card_b'];
        $info['company_sn'] = $data['company_sn'];
        $info['company_license'] = $data['company_license'];
        $info['company_license_yy'] = $data['company_license_yy'] ?: '';
        $info['company_type'] = $data['company_type'];
        $info['company_name'] = $data['company_name'];
        $info['company_addrss'] = $data['company_addrss'];
        $info['company_corporation'] = $data['company_corporation'];
        $info['company_registered_capital'] = $data['company_registered_capital'];
        $info['company_create_time'] = $data['company_create_time'];
        $info['company_operating_period'] = $data['company_operating_period'];
        $info['company_business_scope'] = $data['company_business_scope'];
        $info['is_replenishment'] = $data['is_replenishment'] ?: 1;
        $info['discount_rate'] = $data['discount_rate'] ?: 1;
        $info['is_express_fee'] = $data['is_express_fee'] ?: 1;
        $info['is_agent'] = $data['is_agent'] ?: 0;
        $info['remark'] = $data['remark'] ?: '';
        $info['status'] = $data['status'] ?: 3;
        $info['created_at'] = time();
        $info['apply_time'] = time();
        $info['agent_start_time'] = $data['agent_start_time'];
        $info['agent_end_time'] = $data['agent_end_time'];
        return self::insertGetId(array_filter($info));
    }

    /**
     * 获取信息
     * @param $id
     */
    public static function getInfoById($id)
    {
        $info = self::where(['id' => $id])->first();
        if ($info) {
           return $info->toArray();
        }
        return [];
    }

    /**
     * 修改信息
     * @param $id
     * @param $data
     */
    public static function editInfoById($id, $data)
    {
        $endTime = $data['agent_end_time'] ? strtotime($data['agent_end_time']) : 0;
        $endTimeMax = strtotime('20380101');
        if ($endTime >= $endTimeMax) {
            $endTime = $endTimeMax;
        }
        $info['store_sn'] = $data['store_sn'];
        $info['store_name'] = $data['store_name'];
        $info['money_goods'] = $data['money_goods'] ?: 0;
        $info['money_management'] = $data['money_management'] ?: 0;
        $info['principal_name'] = $data['principal_name'];
        $info['principal_mobile'] = $data['principal_mobile'];
        $info['principal_email'] = $data['principal_email'] ?: '';
        $info['principal_address'] = $data['principal_address'] ?: '';
        $info['principal_card_sn'] = $data['principal_card_sn'];
        $info['principal_card_a'] = $data['principal_card_a'] ?: '';
        $info['principal_card_b'] = $data['principal_card_b'] ?: '';
        $info['company_sn'] = $data['company_sn'];
        $info['company_license'] = $data['company_license'] ?: '';
        $info['company_license_yy'] = $data['company_license_yy'] ?: '';
        $info['company_type'] = $data['company_type'] ?: '';
        $info['company_name'] = $data['company_name'] ?: '';
        $info['company_addrss'] = $data['company_addrss'] ?: '';
        $info['company_corporation'] = $data['company_corporation'] ?: '';
        $info['company_registered_capital'] = $data['company_registered_capital'] ?: '';
        $info['company_create_time'] = $data['company_create_time'] ?: '';
        $info['company_operating_period'] = $data['company_operating_period'] ?: '';
        $info['company_business_scope'] = $data['company_business_scope'] ?: '';
        $info['agent_start_time'] = $data['agent_start_time'] ? strtotime($data['agent_start_time']) : 0;
        $info['agent_end_time'] = $endTime;
        $info['is_replenishment'] = $data['is_replenishment'] ?: 0;
        $info['discount_rate'] = $data['discount_rate'] ?: 1;
        $info['is_express_fee'] = $data['is_express_fee'] ?: 0;
        $info['is_agent'] = $data['is_agent'] ?: 0;
        $info['remark'] = $data['remark'] ?: '';
        $info['status'] = $data['status'] ?: 3;
        //        v($data);
        return self::where(['id' => $id])->update($info);
    }
}